package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.model.Product;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.cart.spi.model.CartItem;
import com.situ.mall.web.service.CartFeignService;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.ProductFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车控制器
 */
@Slf4j
@Controller
public class CartController {

    @Autowired
    private CartFeignService cartFeignService;
    
    @Autowired
    private ProductFeignService productFeignService;
    
    @Autowired
    private CategoryFeignService categoryFeignService;

    /**
     * 购物车页面
     */
    @GetMapping("/cart")
    public String cart(Model model, HttpServletRequest request) {
        try {
            // 获取用户ID（从Session中获取，这里先模拟）
            Integer memberId = getMemberIdFromSession(request);
            if (memberId == null) {
                log.warn("用户未登录，重定向到登录页面");
                return "redirect:/user/login";
            }

            // 1. 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 2. 获取购物车数据
            ResponseEntity<JsonResult<?>> cartResult = cartFeignService.findAll(memberId);
            if (cartResult.getBody() != null && cartResult.getBody().getData() != null) {
                @SuppressWarnings("unchecked")
                List<CartItem> cartItems = (List<CartItem>) cartResult.getBody().getData();
                
                                 // 补充商品详细信息
                 List<CartItemVO> cartItemVOs = new ArrayList<>();
                 for (CartItem item : cartItems) {
                     try {
                         JsonResult<Product> productResult = productFeignService.getProductById(item.getProductId().longValue());
                         if (productResult != null && productResult.getData() != null) {
                             CartItemVO vo = new CartItemVO();
                             vo.setId(item.getId());
                             vo.setProductId(item.getProductId());
                             vo.setQuantity(item.getQuantity());
                             vo.setProduct(productResult.getData());
                             cartItemVOs.add(vo);
                         }
                     } catch (Exception e) {
                         log.error("获取购物车商品详情失败: productId={}", item.getProductId(), e);
                     }
                 }
                
                model.addAttribute("cartItems", cartItemVOs);
                log.info("获取购物车数据: 用户ID={}, 商品数量={}", memberId, cartItemVOs.size());
            } else {
                model.addAttribute("cartItems", new ArrayList<>());
            }

        } catch (Exception e) {
            log.error("购物车页面数据加载失败", e);
            model.addAttribute("cartItems", new ArrayList<>());
        }

        return "cart";
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/cart/add")
    @ResponseBody
    public JsonResult<?> addToCart(@RequestParam("goodId") Integer goodId,
                                   @RequestParam(value = "qty", defaultValue = "1") Integer qty,
                                   HttpServletRequest request) {
        try {
            Integer memberId = getMemberIdFromSession(request);
            if (memberId == null) {
                return JsonResult.fail("请先登录");
            }

                         CartItem cartItem = new CartItem();
             cartItem.setProductId(goodId);
             cartItem.setUserId(memberId);
             cartItem.setQuantity(qty);

            ResponseEntity<JsonResult<?>> result = cartFeignService.save(cartItem);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("添加商品到购物车成功: 用户ID={}, 商品ID={}, 数量={}", memberId, goodId, qty);
                return JsonResult.success("添加到购物车成功");
            } else {
                return JsonResult.fail("添加到购物车失败");
            }

        } catch (Exception e) {
            log.error("添加商品到购物车失败", e);
            return JsonResult.fail("添加到购物车失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PostMapping("/cart/update")
    @ResponseBody
    public JsonResult<?> updateCart(@RequestParam("id") Integer cartItemId,
                                    @RequestParam("qty") Integer qty,
                                    HttpServletRequest request) {
        try {
            Integer memberId = getMemberIdFromSession(request);
            if (memberId == null) {
                return JsonResult.fail("请先登录");
            }

                         CartItem cartItem = new CartItem();
             cartItem.setId(cartItemId);
             cartItem.setUserId(memberId);
             cartItem.setQuantity(qty);

            ResponseEntity<JsonResult<?>> result = cartFeignService.update(cartItem);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("更新购物车商品数量成功: ID={}, 新数量={}", cartItemId, qty);
                return JsonResult.success("更新成功");
            } else {
                return JsonResult.fail("更新失败");
            }

        } catch (Exception e) {
            log.error("更新购物车商品数量失败", e);
            return JsonResult.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除购物车商品
     */
    @PostMapping("/cart/remove")
    @ResponseBody
    public JsonResult<?> removeFromCart(@RequestParam("ids") Integer[] ids,
                                        HttpServletRequest request) {
        try {
            Integer memberId = getMemberIdFromSession(request);
            if (memberId == null) {
                return JsonResult.fail("请先登录");
            }

            ResponseEntity<JsonResult<?>> result = cartFeignService.deleteByIds(ids);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("删除购物车商品成功: 用户ID={}, 删除商品数={}", memberId, ids.length);
                return JsonResult.success("删除成功");
            } else {
                return JsonResult.fail("删除失败");
            }

        } catch (Exception e) {
            log.error("删除购物车商品失败", e);
            return JsonResult.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取会员ID
     */
    private Integer getMemberIdFromSession(HttpServletRequest request) {
        try {
            Object userInfo = request.getSession().getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                LoginUserVO user = (LoginUserVO) userInfo;
                return user.getId().intValue();
            }
        } catch (Exception e) {
            log.warn("获取用户ID失败", e);
        }
        return null;
    }

    /**
     * 购物车项VO（用于页面展示）
     */
    public static class CartItemVO {
        private Integer id;
        private Integer productId;
        private Integer quantity;
        private Product product;

        // getters and setters
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }

        public Integer getProductId() { return productId; }
        public void setProductId(Integer productId) { this.productId = productId; }

        public Integer getQuantity() { return quantity; }
        public void setQuantity(Integer quantity) { this.quantity = quantity; }

        public Product getProduct() { return product; }
        public void setProduct(Product product) { this.product = product; }
    }
} 